/*
 *    This file is part of ReadonlyREST.
 *
 *    ReadonlyREST is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    ReadonlyREST is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with ReadonlyREST.  If not, see http://www.gnu.org/licenses/
 */
package tech.beshu.ror.accesscontrol.audit

import tech.beshu.ror.audit.utils.AuditSerializationHelper.{AuditFieldPath, AuditFieldValueDescriptor}

object AuditFieldUtils {

  private type AUDIT_VALUE = (AuditFieldPath, AuditFieldValueDescriptor) | Map[AuditFieldPath, AuditFieldValueDescriptor]

  def optional(cond: Boolean)(value: AUDIT_VALUE): AUDIT_VALUE =
    Option.when(cond)(value).getOrElse(Map.empty)

  def fields(values: AUDIT_VALUE*): Map[AuditFieldPath, AuditFieldValueDescriptor] =
    values.flatMap(toMap).toMap

  def withPrefix(prefix: String)(
    values: AUDIT_VALUE*
  ): Map[AuditFieldPath, AuditFieldValueDescriptor] =
    withPrefix(prefix, values.flatMap(toMap).toMap)

  private def withPrefix(prefix: String,
                         values: Map[AuditFieldPath, AuditFieldValueDescriptor]): Map[AuditFieldPath, AuditFieldValueDescriptor] = {
    values.map { case (path, desc) =>
      val newPath = AuditFieldPath(prefix, path.path)
      newPath -> desc
    }
  }

  private def toMap(value: AUDIT_VALUE): Map[AuditFieldPath, AuditFieldValueDescriptor] = {
    value match {
      case (path: AuditFieldPath, value: AuditFieldValueDescriptor) =>
        Map(path -> value)
      case values: Map[AuditFieldPath, AuditFieldValueDescriptor] =>
        values
    }
  }
}
